package com.css.common.core.utils.idworker.impl;

import com.css.common.core.utils.idworker.IIdWorker;
import com.css.common.core.utils.idworker.properties.IdWorkerProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * idworker
 * @author gaohongliang
 */
@EnableConfigurationProperties(IdWorkerProperties.class)
@Component
@Slf4j
public class IdWorker implements IIdWorker, InitializingBean {

    private static SnowflakeIdWorker worker;

    @Autowired
    private IdWorkerProperties idWorkerProperties;

    @Override
    public String nextStringId() {
        return String.valueOf(worker.nextId());
    }

    @Override
    public Long nextLongId() {
        return worker.nextId();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (null == worker) {
            worker = new SnowflakeIdWorker(idWorkerProperties.getWorkerId(),
                    idWorkerProperties.getDatacenterId());
        }
    }
}
